import { getSetting, chooseAddress, openSetting, showModal ,showToast} from "../../utils/asyncWx.js";
import { request } from "../../request/request.js";
let movedistance = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    allChecked:false,
    good_id:0,
    address: {},
    order:[],
    totalPrice: 0
  },

  // 点击 收货地址
  async handleChooseAddress() {
    const userId = wx.getStorageSync('app_openid');
    if(!userId){
      wx.showToast({
        title: '未登录',
        icon: 'error',
        // true 防止用户 手抖 疯狂点击按钮 
        mask: true
      });
      return
    }
      try {
        // 1 获取 权限状态
        const res1 = await getSetting();
        const scopeAddress = res1.authSetting["scope.address"];
        // 2 判断 权限状态
        if (scopeAddress === false) {
          await openSetting();
        }
        // 4 调用获取收货地址的 api
        let address = await chooseAddress();
        address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;
  
        // 5 存入到缓存中
        wx.setStorageSync("address", address);
  
      } catch (error) {
        console.log(error);
      }
  },
  // 手指触摸动作开始
  touchstartX(e) {
    // 获取触摸X坐标
    this.recordX = e.touches[0].clientX;
  },
  // 点击操作
  resetX() {
   this.slideAnimation(0, 500);
  },
  // 手指触摸后移动
  touchmoveX(e) {
   let currentX = e.touches[0].clientX;
   movedistance = currentX - this.recordX; // 获取移动距离
   this.slideAnimation(movedistance, 500);
  },
  // 手指触摸动作结束
  touchendX() {
    let recordX;
    if (movedistance <= -100) { // 移动达到距离就动画显示全部操作项
    recordX = -100;
    } else if (movedistance >= -100) { // 移动未达到距离即还原
    recordX = 0;
    }
    this.slideAnimation(recordX, 500);
  },
  // 滑动动画
  slideAnimation(recordX, time) {
    let animation = wx.createAnimation({
    duration: time,
    timingFunction: 'ease'
    });
    animation.translate(recordX + 'rpx', 0).step()
    this.setData({
    animation: animation.export()
    })
  },
   // 删除数据
 deleteItem() {
  let that = this;
  let address = wx.getStorageSync('address');
  wx.showModal({
   title: '提示',
   content: '是否删除该条数据？',
   success(res) {
    if (res.confirm) {
      wx.removeStorage({
        key: 'address'
        })
     that.slideAnimation(0, 500);
     that.setData({
      address: {}
     });
    } else if (res.cancel) {
     console.log('用户点击取消')
    }
   }
  });
 },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.good_id != undefined){
      const good_id = options.good_id
       this.setData({
        good_id
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    // 1 获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");
    //判断是否是直接从商品详情页面跳转进来
    if(this.data.good_id != 0){
      
    }
    // 2 获取选择支付的商品缓存
    const order = wx.getStorageSync('order');
    //计算总价格
    let totalPrice = 0;
    order.forEach(v => {
      totalPrice += v.num * v.goodPrice;
    })

    this.setData({ 
      address,
      order,
      totalPrice
     });

  },
  async handleOrder(){
    
    const address = wx.getStorageSync('address');
    const cart = wx.getStorageSync('cart');
    const order = wx.getStorageSync('order');
    const userId = wx.getStorageSync('app_openid');
    // 判断用户是否登录
    if(!userId){
      wx.showToast({
        title: '未登录',
        icon: 'error',
        // true 防止用户 手抖 疯狂点击按钮 
        mask: true
      });
      return;
    }
    //  判断收货地址
    if(!address.userName){
      await showToast({title:"您还没有选择收货地址"});
      return;
    }
    
    var totalPrice = this.data.totalPrice;
    var orders = JSON.stringify(order);
    var addre = JSON.stringify(address);
    request({url:"/buy/goodsOrder",data:{ orders,userId,addre,totalPrice},method: "POST"})
    .then((result)=>{
      var allChecked = wx.getStorageSync('allChecked');
      if(allChecked){
        wx.removeStorageSync('cart');
      }else{
        for(var index in cart){
          if(cart[index][0].checked){
            console.log(cart[index]);
            cart.splice(index,1);
          }
        }
        wx.setStorageSync('cart', cart)
      }
      wx.removeStorageSync('order');
      wx.navigateTo({
        url: '../order/order',
      })
    })
    .catch((err) => {
      wx.showToast({
        title: '失败',
        icon: 'error',
        // true 防止用户 手抖 疯狂点击按钮 
        mask: true
      });
    });
    
    

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
    this.setData({
      good_id:0
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})